# -*- coding: utf-8 -*-
# vim: set noet ts=4:
#
# scim-python
#
# Copyright (c) 2007-2008 Huang Peng <shawn.p.huang@gmail.com>
#
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330,
# Boston, MA  02111-1307  USA
#
# $Id: $
#
import sqlite3 as sqlite
import PYParser
import PYUtil
import PYSQLiteDB
import sys
import cPickle

(YLEN, Y0, Y1, Y2, Y3, YX, S0, S1, S2, S3, SX, PHRASE, FREQ) = range (0, 13)
			
class PYDictory:
	def __init__ (self, name = "/tmp/py.db"):
		self.db = sqlite.connect (name)
		self.pinyin_parser = PYParser.PinYinParser ()
		
		# init pinyin dict
		_dict = {}
		i = 1
		for py in PYUtil.PINYIN_LIST:
			_dict [unicode (py)] = i
			i += 1
		self._pinyin_dict = _dict

		# init shengmu dict
		_dict = {}
		i = 1
		for shm in PYUtil.SHENGMU_LIST:
			_dict [unicode (shm)] = i
			i += 1
		self._shengmu_dict = _dict

	def init_tree (self):
		try:
			self._tree = cPickle.load (file("pytree.bin", "r"))
		except:
			self._tree = {}
			try:
				for i in self.db.execute ("SELECT * FROM py_phrase ORDER BY ylen,y0,y1,y2,y3,yx,freq DESC"):
					ys = []
					ss = []
					ylen = i[YLEN]
					ys += [i[Y0], i[Y1], i[Y2], i[Y3]]
					ss += [i[S0], i[S1], i[S2], i[S3]]
					yx = i[YX]
					sx = i[SX]
					if yx:
						ys += map (self._pinyin_dict.get, yx.split ("'"))
					if sx:
						ss += map (self._shengmu_dict.get, sx.split ("'"))

					self.add_tree (self._tree, ys[:ylen], ss[:ylen], (i[PHRASE], i[FREQ]))
			except:
				print i
			cPickle.dump (self._tree, file("pytree.bin", "w"))

				
	def add_tree (self, tree, ys, ss, data):
		if not ys:
			if not tree.has_key (-1):
				tree[-1] = []
			tree[-1].append (data)
			return

		y = ys[0]
		s = ss[0]

		if not tree.has_key (y):
			tree[y] = {}
		self.add_tree (tree[y], ys[1:], ss[1:], data)
		if not tree.has_key (s):
			tree[s] = {}
		self.add_tree (tree[s], ys[1:], ss[1:], data)

		
	def select_words_by_string  (self, string):
		pys = self.pinyin_parser.parse (string)


def test ():
	PYDictory ().init_tree ()



if __name__ == "__main__":
	test ()
